import { useIntersectionObserver } from '@vueuse/core'; // 判断组件进入视口

const setupAnimate = (app) => {
  const animateDirective = {
    mounted(el, binding) {
      const { value } = binding;
      /**
       * stop 一个可执行的函数用来停止监听行为
       * el dom对象
       * isIntersecting 一个类型为布尔值的数据 当被监听元素进入视口区域时为true,离开视口区域时为false
       */
      const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
        // 元素进入可视区
        if (isIntersecting) {
          stop();
          const { top } = el.getBoundingClientRect();
          const h = document.documentElement.clientHeight || document.body.clientHeight;
          if (top < h) {
            el.style.visibility = 'visible';
            el.style.animationName = value;
          }
        }
      });
    },
  };

  app.directive('animate', animateDirective);
};

export default setupAnimate;
